package com.cs.study.homework.utils;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: 景天
 * @date: 2024/3/9 11:11
 **/
// 网络工具类
public class NetworkUtils {
    // 提供一个用于获取发送数据报包的方法
    public static DatagramPacket getSendPacket(String msg, String ip, int port) throws UnknownHostException {
        // 构建一个用于发送的数据报包
        byte[] bytes = msg.getBytes();
        InetAddress targetIP = InetAddress.getByName(ip);
        DatagramPacket sendPacket = new DatagramPacket(bytes, 0, bytes.length, targetIP, port);
        return sendPacket;
    }

    // 提供一个用于接收的数据报包的方法
    public static DatagramPacket getReceivePacket() {
        byte[] bytes = new byte[1024];
        // 构建一个空包
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);
        return receivePacket;
    }

    // 提供一个用于解析数据报包的方法
    public static String parseMsg(DatagramPacket packet) {
        byte[] data = packet.getData();
        int offset = packet.getOffset();
        int length = packet.getLength();
        String s = new String(data, offset, length);
        return s;
    }
}
